/*
//  Copyright © 2014 Allen County Public Library.

  //        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
 * Author: James Harpe
 * 
 * Description: This class handles web service calls associated with item renewals.
 * 
 */

package us.in.lib.acpl.Mobile_ACPL.ws;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.google.analytics.tracking.android.EasyTracker;


import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Xml;
import android.view.View;

import us.in.lib.acpl.Mobile_ACPL.AccountCheckoutsFragment;
import us.in.lib.acpl.Mobile_ACPL.R;
import us.in.lib.acpl.Mobile_ACPL.context.Mobile_ACPL;
import us.in.lib.acpl.Mobile_ACPL.patron.Checkout;
import us.in.lib.acpl.Mobile_ACPL.util.RestClient;
import us.in.lib.acpl.Mobile_ACPL.util.RestClient.RequestMethod;

public class RenewalHandler {
	public static final String RENEW_URL = Mobile_ACPL.WS_HOST+"/symws/rest/patron/renewMyCheckout";
	private List<Checkout> toRenew;
	private AccountCheckoutsFragment frag;
	SharedPreferences prefs;

	public RenewalHandler(AccountCheckoutsFragment frag) {

		this.frag = frag;
	}

	public void renew(List<Checkout> toRenew) {
		this.toRenew = toRenew;
		prefs = frag.getActivity().getSharedPreferences("myPrefs",
				Context.MODE_WORLD_WRITEABLE);

		LoginHandler loginHandler = new LoginHandler();
		loginHandler.getNewSessionToken(prefs, frag.getActivity());
		if (prefs.getString("sessionToken", null) != null) {
			new RenewalTask().execute();
		} else {
			frag.getActivity().findViewById(R.id.accountBar)
					.setVisibility(View.GONE);
		}

	}

	private class RenewalTask extends AsyncTask<Void, Void, String[]> {

		@Override
		protected String[] doInBackground(Void... arg0) {
			int failed = 0;
			String failedTitles = "";

			String sessionToken = prefs.getString("sessionToken", null);

			// TODO: Check session token.

			for (int i = 0; i < toRenew.size(); i++) {
				Checkout currCheckout = toRenew.get(i);
				String id = currCheckout.getItemId();

				RestClient client = new RestClient(RENEW_URL);
				client.AddHeader("x-sirs-clientID",
						SearchCatalogHandler.CLIENT_ID);
				client.AddParam("sessionToken", sessionToken);
				client.AddParam("itemID", id);

				try {
					client.Execute(RequestMethod.POST);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				String response = client.getResponse();

				XmlPullParser parser = Xml.newPullParser();

				try {
					parser.setInput(new StringReader(response));

					int eventType = parser.next();

					while (eventType != XmlPullParser.END_DOCUMENT) {
						if (eventType == XmlPullParser.START_TAG) {
							String name = parser.getName();
							if (name.equalsIgnoreCase("Fault")) {
								
							
								EasyTracker.getTracker().sendEvent("Renewal", "Item Failed to Renew", null, null);
								
								failed++;
								failedTitles += currCheckout.getTitle() + "\n";
							}
							if (name.equalsIgnoreCase("dueDate")) {
								
							
								EasyTracker.getTracker().sendEvent("Renewal", "Item Renewed", null, null);
								
								currCheckout.setDueDate(parser.nextText());
								int renewals = Integer.parseInt(currCheckout
										.getTimesRenewed());
								renewals++;
								currCheckout.setTimesRenewed(String
										.valueOf(renewals));
								currCheckout.setOverdue(false);
							}
						}
						eventType = parser.next();
					}
				} catch (XmlPullParserException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			String[] arr = { String.valueOf(toRenew.size() - failed),
					String.valueOf(failed), failedTitles };

			return arr;
		}

		@Override
		protected void onPostExecute(String[] values) {
			frag.handleRenewalResult(values);
		}
	}
}
